package com.ruoyi.common.utils.tencentCos;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.util.Map;

public class CosAppendObject {
    /**
     *
     * @param fileName 文件名
     * @param fileAbsolutePath 文件在服务器的绝对路径
     * @param cosPath cos存储的根目录
     * @return
     */
    public static String AppendObjectFromLocal(Map<String,String> map,String fileName, String fileAbsolutePath, String cosPath) {
        String url="";
        // 1 初始化用户身份信息(secretId, secretKey)
        String SecretId = map.get("secretId");
        String SecretKey = map.get("secretKey");
        COSCredentials cred = new BasicCOSCredentials(SecretId, SecretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(map.get("area")));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket名需包含appid
        String bucketName = map.get("bucketName");

        String key = cosPath+"/"+fileName;
        try {
            File localFile = new File(fileAbsolutePath);
            AppendObjectRequest appendObjectRequest = new AppendObjectRequest(bucketName, key, localFile);
            appendObjectRequest.setPosition(0L);
            AppendObjectResult appendObjectResult = cosclient.appendObject(appendObjectRequest);
            long nextAppendPosition = appendObjectResult.getNextAppendPosition();
            System.out.println(nextAppendPosition);

            url="https://"+bucketName+".cos."+map.get("area")+".myqcloud.com/"+key;
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        // 关闭客户端
        cosclient.shutdown();
        return url;
    }

    public static void main(String[] args) {
       // AppendObjectFromLocal();
    }
}
